/**
 * @author: Niimp
 * @date: 2023/11/28 9:35
 * @statement:
 */
package com.dmgis.hndz.controller;

import com.alibaba.fastjson.JSONObject;
import com.dmgis.hndz.common.constant.FileContentType;
import com.dmgis.hndz.common.utils.MinIOUtil;
import com.dmgis.hndz.service.DynamicWarningService;
import com.dmgis.hndz.service.MessageSendService;
import com.dmgis.hndz.service.impl.SkPngFileService;
import com.dmgis.hndz.common.result.HttpStatusEnum;
import com.dmgis.hndz.common.result.ResponseResult;
import com.dmgis.hndz.common.WebCtrlData;
import com.dmgis.hndz.common.utils.TimeUtil;
import com.dmgis.hndz.common.utils.FileUtil;
import com.dmgis.hndz.pojo.*;
import com.dmgis.hndz.pojoMongo.*;
import com.dmgis.hndz.pojoVo.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

import static com.dmgis.hndz.common.constant.FilePath.GEO_FAC;

@Api(tags = "动态预警一张图")
@RestController
@RequestMapping("/dynamicWarningImage")
public class DynamicWarningController {

    @Autowired
    private DynamicWarningService dynamicWarningService;

    @Autowired
    private SkPngFileService skPngFileService;

    @Autowired
    private MessageSendService messageSendService;

    @Value("${nginx.url}")
    private String nginxUrl;

    @Value("${nginx.filepath}")
    private String nginxFilepath;

    @Autowired
    private MinIOUtil minIOUtil;

    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    /****
     * 查询天气预报  qxba01a  qxbb01a
     * @return
     */
    @ApiOperation(value = "查询三天天气预报(大屏)")
    @PostMapping("/queryThreeCityForecast")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "code", value = "编码", required = true, defaultValue = "NDMwMDAw", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "名称", required = true, defaultValue = "5rmW5Y2X55yB", dataType = "String", paramType = "query")
    })
    public ResponseResult queryThreeCityForecast(@RequestBody JSONObject jsonObject) {
        try {
            String code = jsonObject.getString("code");
            String name = jsonObject.getString("name");
            List<Qxba01a> list = dynamicWarningService.queryThreeCityForecast(code, name);
            if (list.size() == 6) {
                //数据处理
                ArrayList qxaa01AS = new ArrayList<>();
                for (int i = 0; i < list.size() / 2; i++) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("站点编号", list.get(2 * i + 1).getQxba01a010());
                    String qxba01a030 = list.get(2 * i + 1).getQxba01a030();
                    String time = list.get(2 * i + 1).getQxba01a050();
                    //判断是否是当天
                    String date = qxba01a030.substring(0, 10);
                    String format = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if ("24".equals(time)) {
                        format = sdf.format(new Date());
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(parse));
                    } else if ("48".equals(time)) {
                        format = sdf.format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(new Date(parse.getTime() + 24 * 60 * 60 * 1000)));
                    } else if ("72".equals(time)) {
                        format = sdf.format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 2));
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(new Date(parse.getTime() + 24 * 60 * 60 * 1000 * 2)));
                    }
                    if (format.equals(date)) {
                        map.put("日期", "今日");
                    } else {
                        //处理时间
                        String week = TimeUtil.getWeekStr(format);
                        map.put("日期", week);
                    }
                    //风速
                    String fx = WebCtrlData.GetWeatherFx(list.get(2 * i + 1).getQxba01a100());
                    map.put("风向", fx);
                    String fs = WebCtrlData.GetWeatherFs(list.get(2 * i + 1).getQxba01a080());
                    map.put("风力", fs);
                    map.put("站点名称", list.get(2 * i + 1).getQxba01a020());
                    map.put("起报时次", list.get(2 * i + 1).getQxba01a040());
                    map.put("时效", time);
                    map.put("最高气温", list.get(2 * i + 1).getQxba01a060());
                    map.put("最低气温", list.get(2 * i + 1).getQxba01a070());
                    map.put("12小时风力", WebCtrlData.GetWeatherFs(list.get(2 * i + 1).getQxba01a080()));
                    map.put("24小时风力", WebCtrlData.GetWeatherFs(list.get(2 * i + 1).getQxba01a090()));
                    map.put("12小时风向", WebCtrlData.GetWeatherFx(list.get(2 * i + 1).getQxba01a100()));
                    map.put("24小时风向", WebCtrlData.GetWeatherFx(list.get(2 * i + 1).getQxba01a110()));
                    String qxba01a120 = list.get(2 * i).getQxba01a120();
                    if (qxba01a120.length() < 2)
                        qxba01a120 = "0" + qxba01a120;
                    else qxba01a120 = "00";
                    map.put("天气现象", qxba01a120);
                    qxba01a120 = list.get(2 * i + 1).getQxba01a120();
                    if (qxba01a120.length() < 2)
                        qxba01a120 = "0" + qxba01a120;
                    else qxba01a120 = "00";
                    map.put("24天气现象", qxba01a120);
                    map.put("经度", list.get(2 * i + 1).getQxba01a140());
                    map.put("纬度", list.get(2 * i + 1).getQxba01a150());
                    map.put("高程", list.get(2 * i + 1).getQxba01a160());
                    map.put("所属市", list.get(2 * i + 1).getQxba01a170());
                    map.put("所属县", list.get(2 * i + 1).getQxba01a180());
                    map.put("雨量", list.get(2 * i + 1).getQxba01a190());
                    qxaa01AS.add(map);
                }
//                return new ResultObj("查询成功", qxaa01AS, true);
                return new ResponseResult(200, true, "查询成功", qxaa01AS);
            } else if (list.size() == 3) {
                //数据处理
                ArrayList qxaa01AS = new ArrayList<>();
                for (int i = 0; i < list.size(); i++) {
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("站点编号", list.get(i).getQxba01a010());
                    String qxba01a030 = list.get(i).getQxba01a030();
                    String time = list.get(i).getQxba01a050();
                    //判断是否是当天
                    String date = qxba01a030.substring(0, 10);
                    String format = null;
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                    if ("24".equals(time)) {
                        format = sdf.format(new Date());
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(parse));
                    } else if ("48".equals(time)) {
                        format = sdf.format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000));
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(new Date(parse.getTime() + 24 * 60 * 60 * 1000)));
                    } else if ("72".equals(time)) {
                        format = sdf.format(new Date(new Date().getTime() + 24 * 60 * 60 * 1000 * 2));
                        Date parse = sdf.parse(date);
                        map.put("起报日期", sdf.format(new Date(parse.getTime() + 24 * 60 * 60 * 1000 * 2)));
                    }
                    if (format.equals(date)) {
                        map.put("日期", "今日");
                    } else {
                        //处理时间
                        String week = TimeUtil.getWeekStr(format);
                        map.put("日期", week);
                    }
                    //风速
                    String fx = WebCtrlData.GetWeatherFx(list.get(i).getQxba01a100());
                    map.put("风向", fx);
                    String fs = WebCtrlData.GetWeatherFs(list.get(i).getQxba01a080());
                    map.put("风力", fs);
                    map.put("站点名称", list.get(i).getQxba01a020());
                    map.put("起报时次", list.get(i).getQxba01a040());
                    map.put("时效", time);
                    map.put("最高气温", list.get(i).getQxba01a060());
                    map.put("最低气温", list.get(i).getQxba01a070());
                    map.put("12小时风力", WebCtrlData.GetWeatherFs(list.get(i).getQxba01a080()));
                    map.put("24小时风力", WebCtrlData.GetWeatherFs(list.get(i).getQxba01a090()));
                    map.put("12小时风向", WebCtrlData.GetWeatherFx(list.get(i).getQxba01a100()));
                    map.put("24小时风向", WebCtrlData.GetWeatherFx(list.get(i).getQxba01a110()));
                    String qxba01a120 = list.get(i).getQxba01a120();
                    if (qxba01a120.length() < 2)
                        qxba01a120 = "0" + qxba01a120;
                    else qxba01a120 = "00";
                    map.put("天气现象", qxba01a120);
                    qxba01a120 = list.get(i).getQxba01a120();
                    if (qxba01a120.length() < 2)
                        qxba01a120 = "0" + qxba01a120;
                    else qxba01a120 = "00";
                    map.put("24天气现象", qxba01a120);
                    map.put("经度", list.get(i).getQxba01a140());
                    map.put("纬度", list.get(i).getQxba01a150());
                    map.put("高程", list.get(i).getQxba01a160());
                    map.put("所属市", list.get(i).getQxba01a170());
                    map.put("所属县", list.get(i).getQxba01a180());
                    map.put("雨量", list.get(i).getQxba01a190());
                    qxaa01AS.add(map);
                }
//                return new ResultObj("查询成功", qxaa01AS, true);
                return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", qxaa01AS);
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
//            return new ResultObj("获取失败", e.getMessage(), false);
            return new ResponseResult(HttpStatusEnum.ERROR.getCode(), false, "获取失败", e.getMessage());
        }
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", null);
    }


    @ApiOperation(value = "地区及编码")
    @PostMapping("/queryLocationAndCode")
    @ResponseBody
    public ResponseResult queryLocationAndCode() {
        List<LocationAndCode> list = dynamicWarningService.queryLocationAndCode();
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", list);
    }

    @ApiOperation(value = "三天天气预报")
    @PostMapping("/queryThreeDayWeatherForecast2")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "cityName", value = "临沂市", required = false, defaultValue = "临沂市", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "countyName", value = "县区名称(怀化市辖区)", required = false, defaultValue = "蒙阴县", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "todayTime", value = "今日时间", required = true, defaultValue = "2023-11-21", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "sc", value = "时次", required = true, defaultValue = "08", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "ntimes", value = "ntimes", required = true, defaultValue = "24", dataType = "String", paramType = "query")
    })
    public ResponseResult queryThreeDayWeatherForecast2(@RequestBody JSONObject jsonObject) {
        List<ThreeForecastWaterVo> list = dynamicWarningService.queryThreeDayWeatherForecast2(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", list);
    }

    @ApiOperation(value = "三天天气预报")
    @PostMapping("/queryThreeDayWeatherForecast")
    @ResponseBody
    public ResponseResult queryThreeDayWeatherForecast(@RequestBody JSONObject jsonObject) {
        List<ThreeForecastWaterVo> list = dynamicWarningService.queryThreeDayWeatherForecast(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", list);
    }

    @ApiOperation(value = "预警发布统计")
    @PostMapping("/queryWarningReleaseStatistics")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "monthYear", value = "年1月2", required = true, defaultValue = "年1/月2", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "time", value = "年月时间", required = true, defaultValue = "年2023/月2023-11", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "warningType", value = "预警类别", required = true, defaultValue = "全部%、中短期4、短期2、短临1", dataType = "String", paramType = "query")
    })
    public ResponseResult queryWarningReleaseStatistics(@RequestBody JSONObject jsonObject) {
        Map<String, Integer> map = dynamicWarningService.queryWarningReleaseStatistics(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", map);
    }

    //预警统计分析
    @ApiOperation(value = "预警统计分析")
    @PostMapping("/queryWarningStatisticsAnalysis")
    public ResponseResult<Map<String, Object>> queryWarningStatisticsAnalysis(@RequestParam String startTime, @RequestParam String endTime) {
        //用来根据时间进行查询
        Map<String, Integer> map = dynamicWarningService.queryWaringStatisticsAnalysis(startTime, endTime);
        HashMap<String, Object> objectObjectHashMap = new HashMap<>();
        objectObjectHashMap.put("data", map);
        return new ResponseResult<Map<String, Object>>(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", objectObjectHashMap);
    }


    @ApiOperation(value = "动态临灾预警")
    @PostMapping("/queryDynamicNearDisasterWaring")
    @ResponseBody
    public ResponseResult queryDynamicNearDisasterWaring(String hourtype) throws IOException {
        List<Ybba01D> list = dynamicWarningService.queryYbba01D(hourtype);
        List<DlPngFile> fileList = skPngFileService.findDynamicNearDisasterWaringImageByTableId(list);
        for (int i = 0; i < fileList.size(); i++) {
            if (fileList.get(i) == null) {
                list.get(i).setYbba01d060("");
            }
        }

        List<String> resultList = new ArrayList();
        //移除列表所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // List不为空
        boolean allNull = true;
        for (DlPngFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }
        if (!(allNull)) {
            for (DlPngFile file : fileList) {
                //保存图片到本地
                String fileSuffix = file.getFile_id() + ".png";
//                String filePath = nginxFilepath + fileSuffix;
//                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//                    FileUtil.bytesToFile(file.getData(), filePath);
//                }
                if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
                    try {
                        minIOUtil.putObject(file.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.PNG);
                    }catch (Exception exception){
                        exception.printStackTrace();
                        return ResponseResult.fail("文件上传失败！");
                    }

                }
                resultList.add(minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));
//                resultList.add(fileSuffix);
            }

//            for (int i = 0; i < resultList.size(); i++) {   //拼接nginx地址与suffix
//                resultList.set(i, nginxUrl + "/" + resultList.get(i));
//            }
        }

        DynamicNearDisasterWaring dynamicNearDisasterWaring = new DynamicNearDisasterWaring(list, resultList);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", dynamicNearDisasterWaring);
    }


    @ApiOperation(value = "今日省份预警-短期")
    @PostMapping("/queryTodayProvinceShortWaring")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "当日时间", required = true, defaultValue = "2023-09-06", dataType = "String", paramType = "query"),
    })
    public ResponseResult queryTodayProvinceShortWaring(@RequestBody JSONObject jsonObject) throws IOException {
        //短期预警(一条数据)
        DynamicWaringShortVo dynamicWaringShortVo = dynamicWarningService.queryTodayProvinceShortWaring(jsonObject);
        ShortWarnProductJpgFile file = skPngFileService.findTodayProvinceShortWaringByTableId(dynamicWaringShortVo); //查地图图片
        DocWarnProductCityFile fileDoc = skPngFileService.findTodayProvinceShortWaringDocByTableId(dynamicWaringShortVo); //查文档
        String path = "";
        String docPath = "";
        // 对象不为空
        if (!(file == null)) {
            //保存图片到本地
            String fileSuffix = file.getTable_id() + ".jpg";
            String filePath = nginxFilepath + "\\" + fileSuffix;
            if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
                FileUtil.bytesToFile(file.getData(), filePath);
            }
            path = nginxUrl + "/" + fileSuffix; //拼接nginx地址与suffix
        }
        if (!(fileDoc == null)) {
            //保存图片到本地
            String fileSuffix = fileDoc.getTable_id() + ".pdf";

            String filePath = nginxFilepath + "\\" + fileSuffix;
            if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
                FileUtil.bytesToFile(file.getData(), filePath);
            }
            docPath = nginxUrl + "/" + fileSuffix; //拼接nginx地址与suffix
        }
        DynamicWaringShortPlusVo dynamicWaringShortPlusVo = new DynamicWaringShortPlusVo(dynamicWaringShortVo, path, docPath);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", dynamicWaringShortPlusVo);
    }


    @ApiOperation(value = "今日省份预警-中短期")
    @PostMapping("/queryTodayProvinceMidShortWaring")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "当日时间", required = true, defaultValue = "2023-10-07", dataType = "String", paramType = "query"),
    })
    public ResponseResult queryTodayProvinceMidShortWaring(@RequestBody JSONObject jsonObject) throws IOException {
        //中短期预警(时间内所有)
        List<TwoStringVo> list = dynamicWarningService.queryTodayProvinceMidShortWaring(jsonObject);
        //图片
        List<MidShortProductJpgFile> fileList = skPngFileService.findTodayProvinceMidShortWaringByTableId(list);
        //文档
        List<DocWarnProductCityFile> docList = skPngFileService.findTodayProvinceMidShortWaringDocByTableId(list);

        //移除fileList所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        //移除docList所有为Null的元素
        docList = docList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        List<String> resultImageList = new ArrayList();
        List<String> resultDocList = new ArrayList();
        // List不为空
        boolean allNull = true;
        boolean allNullDoc = true;
        for (MidShortProductJpgFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }

        if (!(allNull)) {
            for (MidShortProductJpgFile file : fileList) {
                //保存图片到本地
                String fileSuffix = file.getTable_id() + ".jpg";
                String filePath = nginxFilepath + "\\" + fileSuffix;
                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
                    FileUtil.bytesToFile(file.getData(), filePath);
                }
                resultImageList.add(fileSuffix);
            }

            for (int i = 0; i < resultImageList.size(); i++) {   //拼接nginx地址与suffix
                resultImageList.set(i, nginxUrl + "/" + resultImageList.get(i));
            }
        }
        for (DocWarnProductCityFile element : docList) {
            if (element != null) {
                allNullDoc = false;
                break;
            }
        }
        if (!(allNullDoc)) {
            for (DocWarnProductCityFile file : docList) {
                //保存图片到本地
                String fileSuffix = file.getTable_id() + ".pdf";
                String filePath = nginxFilepath + "\\" + fileSuffix;
                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
                    FileUtil.bytesToFile(file.getData(), filePath);
                }
                resultDocList.add(fileSuffix);
            }

            for (int i = 0; i < resultDocList.size(); i++) {   //拼接nginx地址与suffix
                resultDocList.set(i, nginxUrl + "/" + resultDocList.get(i));
            }
        }
        ThreeStringListVo threeStringListVo = new ThreeStringListVo(list, resultImageList, resultDocList);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", threeStringListVo);
    }


    @ApiOperation(value = "最新监控")
    @PostMapping("/queryLatestMonitoring")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间", required = true, defaultValue = "2023-11-27", dataType = "String", paramType = "query")
    })
    public ResponseResult queryLatestMonitoring(@RequestBody JSONObject jsonObject) {
        List<LatestMonitoring> statement = dynamicWarningService.queryLatestMonitoring(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }

    @ApiOperation(value = "最新监控详细信息")
    @PostMapping("/queryLatestMonitoringInfo")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间", required = false, defaultValue = "2023-06-30 09:09", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "截至时间", required = false, defaultValue = "2023-07-30 09:09", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "county", value = "县", required = false, defaultValue = "沅陵县", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "waringLevel", value = "预警等级", required = false, defaultValue = "", dataType = "String", paramType = "query")
    })
    public ResponseResult queryLatestMonitoringInfo(@RequestBody JSONObject jsonObject) {
        List<LatestMonitoring> statement = dynamicWarningService.queryLatestMonitoringInfo(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }


    @ApiOperation(value = "预报监控")
    @PostMapping("/queryforecastMonitoring")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间", required = true, defaultValue = "2023-11-27", dataType = "String", paramType = "query")
    })
    public ResponseResult queryforecastMonitoring(@RequestBody JSONObject jsonObject) {
        List<String> statement = dynamicWarningService.queryforecastMonitoring(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }


    @ApiOperation(value = "左实况降水图片")
    @ResponseBody
    @PostMapping("/getPngFilesByDateTime")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间(空字符串则查pg、传入时间则按照时间查格式2023-11-16 17:00:00)", required = true, defaultValue = "", dataType = "String", paramType = "query")
    })
    public ResponseResult downloadPngFiles(@RequestBody JSONObject jsonObject) throws IOException, ParseException {
        List<SkPngFile> fileList = new ArrayList<>();
        String maxNewDateString = "";
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = jsonObject.getString("time");
        List<String> resultList = new ArrayList<>(); //地址列表
        Date maxNewDate = new Date(0);
        if (StringUtils.isEmpty(time)) {  //若未传时间， 查询ggcf01a 得到时间
            String ggcf01a020 = "sk_time";
            String pgTime = dynamicWarningService.queryTimeBysk_time(ggcf01a020);
            fileList = skPngFileService.findPngFilesByDatetimePg(pgTime);
        } else {      //若传入了时间，则按照传入的时间来查
            fileList = skPngFileService.findFilesByDatetimeMg(time);
        }
        //移除列表所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull).sorted(Comparator.comparing(SkPngFile::getNtime))
                .collect(Collectors.toList());
        // List不为空
        boolean allNull = true;
        boolean allNullDoc = true;
        for (SkPngFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }
        Map<String, String> map = new LinkedHashMap<>();

        if (!(allNull)) {

            Map<Integer, SkPngFile> ntimeMap = new HashMap<>();
            for (SkPngFile file : fileList) {
                if (!ntimeMap.containsKey(file.getNtime()))
                    ntimeMap.put(file.getNtime(), file);
            }

            Integer[] ntimelist = new Integer[]{1, 3, 6, 12, 24, 48, 72};

            for (Integer nn : ntimelist) {
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(sdf.parse(time));
                calendar.add(Calendar.HOUR_OF_DAY, -nn);
                String format = sdf.format(calendar.getTime());


                if (ntimeMap.containsKey(nn)) {
                    SkPngFile file = ntimeMap.get(nn);
                    Date parse = sdf.parse(file.getDatetime());
                    maxNewDate = parse.compareTo(maxNewDate) >= 0 ? parse : maxNewDate;  //返回最新时间
                    maxNewDateString = sdf.format(maxNewDate);
                    //保存文件
                    String fileSuffix = file.getId() + file.getNtime() + ".png";
//                    String filePath = nginxFilepath + fileSuffix;
//                    if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//                        FileUtil.bytesToFile(file.getData(), filePath);
//                    }

                    if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
                        try {
                            minIOUtil.putObject(file.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.PNG);
                        }catch (Exception exception){
                            exception.printStackTrace();
                            return ResponseResult.fail("文件上传失败！");
                        }

                    }
                    map.put(format, minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));
                } else {
                    map.put(format, "");
                }
            }


//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                if (!entry.getValue().isEmpty())
//                    entry.setValue(nginxUrl + "/" + entry.getValue());
//            }
        }
        Map<String, List<String>> dateListMap = new HashMap<>();
        dateListMap.put(maxNewDateString, resultList);
        SkPngResultVo skPngResultVo = new SkPngResultVo(maxNewDateString, map);
        return ResponseResult.success(skPngResultVo);
    }

    @ApiOperation(value = "左实况降水信息")
    @PostMapping("/queryPrecipitationInfoByTimeAndName")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, defaultValue = "2023-11-16 10:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, defaultValue = "2023-11-16 10:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "name", value = "县名称", required = true, defaultValue = "市中区", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "isCounty", value = "是否为区县", required = true, dataType = "String", paramType = "query")
    })
    public ResponseResult queryPrecipitationInfoByTimeAndName(@RequestBody JSONObject jsonObject) {
        PrecipitationInfoByTimeAndNameVo statement = dynamicWarningService.queryPrecipitationInfoByTimeAndName(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }


    /**
     * 根据时间段、站点编号查询逐小时降水以及逐小时累积
     */
    @ApiOperation(value = "左逐小时降水以及逐小时累积")
    @PostMapping("/queryFallingWaterGrowingByTimeAndStationCode")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, defaultValue = "2023-06-29 02:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, defaultValue = "2023-07-01 07:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "stationCode", value = "站点编号", required = true, defaultValue = "P4105", dataType = "String", paramType = "query")
    })
    public ResponseResult queryFallingWaterGrowingByTimeAndStationCode(@RequestBody JSONObject jsonObject) {
        List<TwoIntegetAndTimeVo> statement = dynamicWarningService.queryFallingWaterGrowingByTimeAndStationCode(jsonObject);
        return new ResponseResult(HttpStatusEnum.SUCCESS.getCode(), true, "查询成功", statement);
    }


    /**
     * 预报1个接口
     * 根据时间查询图片（时间未传 查询ggcf01a 得到时间）
     */
    @ApiOperation(value = "左预报降水图片")
    @PostMapping("/queryForecastFallingWaterByTime")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "time", value = "时间yyyy-MM-dd", required = true, defaultValue = "2023-11-28", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "nTime", value = "时次8/20", required = true, defaultValue = "8", dataType = "String", paramType = "query")
    })
    public ResponseResult queryForecastFallingWaterByTime(@RequestBody JSONObject jsonObject) throws IOException, ParseException {
        Map<String, String> map = new LinkedHashMap<>();//时间 + 地址列表
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String time = jsonObject.getString("time");
        String nTime = jsonObject.getString("nTime");
        List<YbPngFile> fileList = new ArrayList<>();
//        if (StringUtils.isEmpty(time)) {  //若为传时间， 查询ggcf01a 得到时间
//            String ggcf01a020 = "yb_time";
//            String pgTime = dynamicWarningService.queryTimeBysk_time(ggcf01a020);
//            fileList = skPngFileService.findForecastPngFilesByDatetimePg(pgTime);
//        } else {      //若传入了时间，则按照传入的时间来查
//            fileList = skPngFileService.findForecastPngFilesByDatetimeMg(time,nTime);
//        }
        fileList = skPngFileService.findForecastPngFilesByDatetimeMg(time, nTime);

        //移除列表所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull).sorted(Comparator.comparing(YbPngFile::getNtime))
                .collect(Collectors.toList());


        // List不为空
        boolean allNull = true;
        for (YbPngFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }
        if (!(allNull)) {

            for (YbPngFile file : fileList) {
                Calendar calendar = Calendar.getInstance();
                //保存文件
                int n = file.getNtime() / 24;
                if (n > 0) {
                    calendar.setTime(sdf.parse(file.getDatetime()));
                    calendar.add(Calendar.DAY_OF_MONTH, n);
                    String format = sdf.format(calendar.getTime());
                    file.setDatetime(format);
                }
                String fileSuffix = file.getId() + file.getNtime() + ".png";
//                String filePath = nginxFilepath + fileSuffix;
//                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//                    FileUtil.bytesToFile(file.getData(), filePath);
//                }
                if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
                    try {
                        minIOUtil.putObject(file.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.PNG);
                    }catch (Exception exception){
                        exception.printStackTrace();
                        return ResponseResult.fail("文件上传失败！");
                    }

                }
                map.put(file.getDatetime(), minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));
            }

//            for (Map.Entry<String, String> entry : map.entrySet()) {
//                entry.setValue(nginxUrl + "/" + entry.getValue());
//            }

        }

        return ResponseResult.success(map);
    }


    /**
     * 雷达图
     * 查询最近10张雷达图
     * 省级pg库 qxab02b 根据日期时次倒序取10张 得到qxab02b100编号 去省级mg库image_rader_png_file 根据编号查询图片
     */
    @ApiOperation(value = "雷达图")
    @PostMapping("/queryRadarChat")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, defaultValue = "2023-06-29 02:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, defaultValue = "2023-07-01 07:00:00", dataType = "Date", paramType = "query"),
    })
    public ResponseResult queryRadarChat(@RequestBody JSONObject jsonObject) throws IOException {
        RadarChatVo radarChatVo = new RadarChatVo();
        List<String> resultList = new ArrayList<>(); //地址列表
        List<Qxab02b> list = dynamicWarningService.queryRadarChat(jsonObject); //pg库获取到的时间、文件编号列表
        radarChatVo.setList(list);
        List<ImageRaderPngFile> fileList = skPngFileService.findRadarChatByFileId(list);

        //移除列表所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // List不为空
        boolean allNull = true;
        boolean allNullDoc = true;
        for (ImageRaderPngFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }
        if (!(allNull)) {
            for (ImageRaderPngFile file : fileList) {

                //保存文件
                String fileSuffix = file.getFile_id() + ".png";
//                String filePath = nginxFilepath + fileSuffix;
//                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//                    FileUtil.bytesToFile(file.getData(), filePath);
//                }
                if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
                    try {
                        minIOUtil.putObject(file.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.PNG);
                    }catch (Exception exception){
                        exception.printStackTrace();
                        return ResponseResult.fail("文件上传失败！");
                    }

                }
                resultList.add(minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));

            }
//            for (int i = 0; i < resultList.size(); i++) {   //拼接nginx地址与suffix
//                resultList.set(i, nginxUrl + "/" + resultList.get(i));
//            }
            radarChatVo.setResultList(resultList);
        }

        return ResponseResult.success(radarChatVo);
    }


    /**
     * 云图
     * 查询最近10张云图
     * 省级pg库qxab03a 根据日期时次倒序取10张 得到qxab03a100编号 去省级mg库image_cloud_png_file 根据编号查询图片
     */
    @ApiOperation(value = "云图")
    @PostMapping("/queryCloudChat")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = true, defaultValue = "2023-06-29 02:00:00", dataType = "Date", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = true, defaultValue = "2023-07-01 07:00:00", dataType = "Date", paramType = "query"),
    })
    public ResponseResult queryCloudChat(@RequestBody JSONObject jsonObject) throws IOException {
        CloudChatVo radarChatVo = new CloudChatVo();
        List<String> resultList = new ArrayList<>(); //地址列表
        List<Qxab03a> list = dynamicWarningService.queryCloudChat(jsonObject); //pg库获取到的时间、文件编号列表
        radarChatVo.setList(list);
        List<ImageCloudPngFile> fileList = skPngFileService.findCloudChatByFileId(list);

        //移除列表所有为Null的元素
        fileList = fileList.stream()
                .filter(Objects::nonNull)
                .collect(Collectors.toList());
        // List不为空
        boolean allNull = true;
        boolean allNullDoc = true;
        for (ImageCloudPngFile element : fileList) {
            if (element != null) {
                allNull = false;
                break;
            }
        }
        if (!(allNull)) {
            for (ImageCloudPngFile file : fileList) {

                //保存文件
                String fileSuffix = file.getFile_id() + ".jpg";
//                String filePath = nginxFilepath + fileSuffix;
//                if (!Files.exists(Paths.get(filePath))) {  //若文件已存在则不再写入
//                    FileUtil.bytesToFile(file.getData(), filePath);
//                }
                if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
                    try {
                        minIOUtil.putObject(file.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.PNG);
                    }catch (Exception exception){
                        exception.printStackTrace();
                        return ResponseResult.fail("文件上传失败！");
                    }

                }
                resultList.add(minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));
            }
//            for (int i = 0; i < resultList.size(); i++) {   //拼接nginx地址与suffix
//                resultList.set(i, nginxUrl + "/" + resultList.get(i));
//            }
            radarChatVo.setResultList(resultList);
        }

        return ResponseResult.success(radarChatVo);
    }


    /**
     * 服务产品
     * 查询最近10个产品
     * 省级PG库qxbb01a
     * 根据qxbb01a060的编号去省级mg库里查询文件pdf_service_product
     */
    @ApiOperation(value = "服务产品")
    @PostMapping("/queryServiceProduct")
    @ResponseBody
    @ApiImplicitParams({
            @ApiImplicitParam(name = "wordType", value = "产品类型", required = false, defaultValue = "", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "startTime", value = "开始时间", required = false, defaultValue = "2024-06-29 02:00:00", dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "endTime", value = "结束时间", required = false, defaultValue = "2024-07-01 07:00:00", dataType = "String", paramType = "query"),
    })
    public ResponseResult queryServiceProduct(String wordType, String startTime, String endTime) throws IOException {
//        Map<String, String> resultMap = new HashMap<>();
//        List<String> resultList = new ArrayList<>(); //地址列表
        List<Qxbb01a> list = dynamicWarningService.queryServiceProduct(wordType, startTime, endTime); //pg库获取到的时间、文件编号列表
//        List<PdfServiceProduct> fileList = skPngFileService.findServiceProductByTableId(list);
//        //移除列表所有为Null的元素
//        fileList = fileList.stream()
//                .filter(Objects::nonNull)
//                .collect(Collectors.toList());
//        boolean allNull = true;
//        for (Qxbb01a element : list) {  //判断是否获取到数据
//            if (element != null) {
//                allNull = false;
//                break;
//            }
//        }
//        if (!(allNull)) {
//            for (int i = 0; i < fileList.size(); i++) {
//
//                for (int i1 = 0; i1 < list.size(); i1++) {
//                    if (list.get(i1).getQxbb01a060().equals(fileList.get(i).getFile_id())) {
//                        //保存图片到本地
//                        String t = list.get(i1).getQxbb01a020();
//                        String[] parts = t.split(" ");
//                        String cleanedString = parts[0].replace("-", "");
//                        String formattedDateTime = cleanedString + parts[1].substring(0, 2);
//                        String fileSuffix = formattedDateTime + ".txt";
//                        String fileSuffix1 = formattedDateTime + "_1.txt";
//                        String filePath = nginxFilepath + fileSuffix;
//                        String filePath1 = nginxFilepath + fileSuffix1;
////                        if (!Files.exists(Paths.get(filePath))) {
////                            FileUtil.bytesToFile(fileList.get(i).getData(), filePath1);
////                            FileUtil.ASNItoUTF(filePath1, filePath);
////                        }
//                        if (!minIOUtil.isObjectExist(fileSuffix)) {  //若文件已存在则不再写入
//                            try {
//                                PdfServiceProduct mongoTemplateOne = mongoTemplate.findOne(new Query(
//                                        Criteria.where("file_id").is(list.get(i1).getQxbb01a060())
//                                ), PdfServiceProduct.class);
//                                minIOUtil.putObject(mongoTemplateOne.getData(),GEO_FAC.getPath(),fileSuffix, FileContentType.TXT);
//                            }catch (Exception exception){
//                                exception.printStackTrace();
//                                return ResponseResult.fail("文件上传失败！");
//                            }
//
//                        }
//                        resultList.add(fileSuffix);
//                        resultMap.put(list.get(i1).getQxbb01a020() + i, minIOUtil.getFileUrl(GEO_FAC.getPath(),fileSuffix));
//                        list.remove(i1);
//                    }
//                }
//
//            }
//        }
//        // 将数据按日期排序
//        Map<String, String> resultMapData = resultMap
//                .entrySet().stream()
//                .sorted(Collections.reverseOrder(comparingByValue()))
//                .collect(
//                        toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
//        return ResponseResult.success(resultMapData);
        return ResponseResult.success(list);
    }


    /**
     * 查询行政区
     *
     * @param type     地区类型：省1，市2，区县3，乡镇4，村5
     * @param parentId 父地区id
     * @return
     */
    @ApiOperation(value = "查询行政区")
    @GetMapping("/queryRegion")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "type", value = "地区类型：省1，市2，区县3，乡镇4，村5", required = true),
            @ApiImplicitParam(name = "parentId", value = "父地区id", required = true),
    })
    @ResponseBody
    public ResponseResult queryRegion(String type, Long parentId) {
        List<Ggsy01a> arealist = messageSendService.getRegion(type, parentId);
        return ResponseResult.success(arealist);
    }


}


